package com.example.scenictourback.service.impl;

import com.example.scenictourback.dto.LoginDTO;
import com.example.scenictourback.dto.RegisterDTO;
import com.example.scenictourback.entity.User;
import com.example.scenictourback.repository.UserRepository;
import com.example.scenictourback.security.JwtUtils;
import com.example.scenictourback.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class AuthServiceImpl implements AuthService {
    
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public Map<String, Object> login(LoginDTO loginDTO) {
        try {
            // 先查找用户
            Optional<User> userOpt = userRepository.findByUsername(loginDTO.getUsername());
            if (!userOpt.isPresent()) {
                throw new RuntimeException("用户名或密码错误");
            }
            
            User user = userOpt.get();
            String storedPassword = user.getPassword();
            String inputPassword = loginDTO.getPassword();
            
            // 尝试直接比较MD5值（前端已进行MD5加密）
            if (storedPassword.equals(inputPassword)) {
                // 密码匹配成功，手动创建认证对象
                UserDetails userDetails = org.springframework.security.core.userdetails.User
                    .withUsername(user.getUsername())
                    .password(user.getPassword())
                    .roles(user.getRole() == 1 ? "USER" : "ADMIN")
                    .build();
                
                // 生成JWT token
                String token = jwtUtils.generateToken(userDetails);
                
                // 构建返回数据
                Map<String, Object> result = new HashMap<>();
                result.put("token", token);
                result.put("userId", user.getId());
                result.put("username", user.getUsername());
                result.put("role", user.getRole());
                
                return result;
            } else {
                // 如果直接比较失败，尝试使用Spring Security的认证管理器
                Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword())
                );
                
                // 认证通过，生成JWT token
                UserDetails userDetails = (UserDetails) authentication.getPrincipal();
                String token = jwtUtils.generateToken(userDetails);
                
                // 构建返回数据
                Map<String, Object> result = new HashMap<>();
                result.put("token", token);
                result.put("userId", user.getId());
                result.put("username", user.getUsername());
                result.put("role", user.getRole());
                
                return result;
            }
        } catch (BadCredentialsException e) {
            throw new RuntimeException("用户名或密码错误");
        }
    }
    
    @Override
    @Transactional
    public boolean register(RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(registerDTO.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setPhone(registerDTO.getPhone());
        user.setRole(1); // 默认为游客
        user.setStatus(1); // 默认为正常
        
        // 保存用户
        userRepository.save(user);
        
        return true;
    }
    
    @Override
    public void logout(String token) {
        // JWT是无状态的，实际上无需做任何操作
        // 如果需要实现黑名单，可以在这里添加token到黑名单中
    }
} 